﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServeNHL.Models;
using System.Web.Security;
using ServeNHL.Helpers;





namespace ServeNHL.Controllers
{
    public class SecurityController : Controller
    {
        // GET: Login


       

        public ActionResult Create()
        {
           
            
            string un = Request["email"].ToString();
            string password = Request["password"].ToString();
            string confirmpassword = Request["confirm"].ToString();
            string lastname = Request["lastName"].ToString();
            string firstName = Request["firstName"].ToString();
            string phone = Request["phoneNumber"].ToString();
            bool isgoodphone = false;
            bool isgoodname = false;
            bool isgoodpw = false;
            bool isgoodemail = false;
           
            var nametest = new UserViewModel();

            /******************************************************
            *     Validation
            *****************************************************/
            var checkemail = new RegexUtilities();
            //checks if email is in correct format
            isgoodemail = checkemail.IsValidEmail(un);
            //take only digits from phone
            phone = new String(phone.Where(Char.IsDigit).ToArray());
            //phone number is long enough >10 allows for international numbers
            if (phone.Length >= 10 && !String.IsNullOrEmpty(phone) && phone.Length <=32)
            {
                isgoodphone = true;
            }
            if (password == confirmpassword && !String.IsNullOrEmpty(password))
            {
                isgoodpw = true;
            }
            
            string pw = Helpers.UserHelper.getPasswordSaltHash(password);
            using (var db = new Models.fclick_dbEntities())
            {
                //check if username is avaialable 
                isgoodname = nametest.isAvailableUsername(un);
                if (isgoodname && isgoodpw && isgoodemail && isgoodphone && !String.IsNullOrEmpty(lastname) && !String.IsNullOrEmpty(firstName) && firstName.Length <= 30 && lastname.Length <= 30)
                {

                    //insert into family first
                    var family = new FAMILY() {
                        FAMILY_NAME = lastname,
                        CREATED_DATE = DateTime.Now,
                        LAST_MOD_DATE = DateTime.Now,

                    };

                    db.FAMILies.Add(family);
                    db.SaveChanges();

                    var user = new USER
                    {

                        USERNAME = Request["email"],
                        PASSWORD = pw,
                        //Setting to active for testing. future: set to pending to be approved by admin, screening process/background checks
                        STATUS = "Active",
                        CREATED_DATE = DateTime.Now,
                        LAST_MOD_DATE = DateTime.Now,
                        FAMILY_ID = family.FAMILY_ID,

            };
                    db.USERs.Add(user);
                    db.SaveChanges();
                   

                    var userSignUp = new USER_CONTACT
                    {
                        USER_ID = user.USER_ID,
                        FIRST_NAME = Request["firstName"],
                        LAST_NAME = Request["lastName"],
                        EMAIL = Request["email"],
                        PHONE = phone,
                        //CARRIER =  NOT sure how to grab carrier?
                        CREATED_DATE = DateTime.Now,
                        LAST_MOD_DATE = DateTime.Now,

        };
                    db.USER_CONTACT.Add(userSignUp);
                    db.SaveChanges();


                    var role = new USER_ROLE
                    {
                        ROLE_NAME = "familyHead",
                        //setting active for testing 
                        STATUS = "Active",
                        CREATED_DATE = DateTime.Now,
                        LAST_MOD_DATE = DateTime.Now,
                        USER_ID = user.USER_ID,
                        ORG_ID = 1,

                    };
                    db.USER_ROLE.Add(role);
                    db.SaveChanges();
                    
                }
            
                //error messages for validation
                else
                {
                    if (!isgoodpw)
                    {
                        ViewBag.Message = "Passwords do not match or was empty";
                        return View("Signup");
                    }
                    else if (!isgoodemail)
                    {
                        ViewBag.Message = "Email is not formatted correctly (e.g. user@mail.com) or was empty";
                        return View("Signup");
                    }
                    else if (!isgoodphone)
                    {
                        ViewBag.Message = "Phone number was entered incorrectly (e.g. (111)-111-1111)";
                        return View("Signup");
                    }
                    else if(!isgoodname) {
                        ViewBag.Message = "Username is already in use";
                        return View("Signup");
                    }
                    else
                    {
                        ViewBag.Message = "First name and last name are required";
                        return View("Signup");
                    }
                }
            }

            ViewBag.Message = "Account Created. Please sign in";

            return View("Login");
        }
        public ActionResult Signup()
        {
       
            
            return View();
        }

        public ActionResult Login(string msg)
        {
            ViewBag.Login = msg;
            return View();
        }
        
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ProcessingLogin(string ReturnUrl)
        {
            string passwordHash;
            bool isValidUser = false;
            string username = Request["username"];
            string password = Request["password"];
            var tmpUser = new USER();
            var tempRole = new USER_ROLE();
            ReturnUrl = Request["ReturnUrl"];

            using (var dbconn = new fclick_dbEntities())
            {
                if (dbconn.USERs.Any(u => u.USERNAME == username))
                {
                    tmpUser = dbconn.USERs.Where(u => u.USERNAME == username).FirstOrDefault();
                    DateTime createDate = DateTime.Now;
                    passwordHash = UserHelper.getPasswordSaltHash(Request["password"]);
                    isValidUser = dbconn.USERs.Any(u => u.USERNAME == username && u.PASSWORD == passwordHash);
                }
            }

            //query to get user's role
            using(var db = new fclick_dbEntities())
            {
                var role = from r in db.USER_ROLE
                           join u in db.USERs on r.USER_ID equals u.USER_ID
                           select r.ROLE_NAME;
                tempRole.ROLE_NAME = role.FirstOrDefault();
            }
            if (isValidUser)
            {
                Session["userid"] = tmpUser.USER_ID;
                Session["username"] = tmpUser.USERNAME;
                ViewBag.message = tmpUser.USERNAME.ToString();
                FormsAuthentication.SetAuthCookie(username, true);
                if (tempRole.ROLE_NAME == "SuperAdmin")
                {
                    Session["Role"] = "SuperAdmin";
                     return RedirectToAction("Portal", "Events");
                  //  return View("portal");
                }
                else if (tempRole.ROLE_NAME == "OrgAdmin")
                {
                    Session["Role"] = "OrgAdmin";
                    return RedirectToAction("Index", "SiteManager");
                }
                else if (tempRole.ROLE_NAME == "eventAdmin")
                {
                    Session["Role"] = "eventAdmin";
                    return RedirectToAction("Portal", "Events");
                }
                else if (tempRole.ROLE_NAME == "familyHead")
                {
                    Session["Role"] = "familyHead";
                    return RedirectToAction("Portal", "Events");
                }
                else if (tempRole.ROLE_NAME == "user")
                {
                    Session["Role"] = "user";
                    return RedirectToAction("Portal", "Events");
                    //need to figure out routing
                }
                else {
                    return RedirectToAction("Portal", "Events");
                }
            } //end of if(validuser)
            else
            {
                ViewBag.Message = "Invalid Login Credentials";
                return View("Login");
            }
        }
        //forgot password 
        public ActionResult resetpw()
        {
            var user = new UserViewModel();
            string email=  Request["email"].ToString();
            string confirm = Request["confirm"].ToString();
            bool emailExists = false;

            //need to check if username exists in db 
            //email exists is true if it is not available 
            emailExists = !user.isAvailableUsername(email);

             if(String.IsNullOrEmpty(email) || String.IsNullOrEmpty(confirm) )
            {
                ViewBag.error = "Please enter the email associated with your serve account";
                return View("ForgotPW");

            }

            else if(email == confirm && emailExists) 
            {
                user.sendReset(email);

                ViewBag.error = "An email has been sent with a temporary password";

                return View("ForgotPW");
            }
             
            else
            {
                ViewBag.error = "Your email did not match or a different email was used for your Serve NHL account";
                return View("ForgotPW");
               
            }
        }

        //forgotPW view
        public ActionResult ForgotPW()
        {
            return View();
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            Session["Role"] = null;
            Session["username"] = null;
            Session["userid"] = null;

            ViewBag.Message = "You are now signed out";
            return View("Login");
        }

        public ActionResult NewAccount()
        {
            return View();
        }

        public ActionResult ResetPassword()
        {
            return View();
        }

    }
}
